#!/user/bin/env node

const log = console.log,
      fs = require('fs'),
      qs = require('querystring'),
      http = require('http');

const uploadPage = `
  <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>Upload File</title>
      </head>
      <body>
        <h1>Upload File</h1>
        <form method="post" enctype="multipart/form-data" action="/upload">
          <input type="file" name="upload">
          <input type="submit" value="Upload">
        </form>
      </body>
    </html>`;

const onPage = `
  <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>Upload File</title>
      </head>
      <body>
        <h1>Upload File OK!</h1>
        <a href="/">continue to upload</a>
      </body>
</html>`;

let errPage =`
   <!DOCTYPE html>
     <html>
      <head>
        <meta charset="UTF-8">
        <title>Error</title>
      </head>
      <body>
        <h1>Sorry! There is  nothing!</h1>
        <a href="/">back to upload file</a>
      </body>
    </html>`;


http.createServer((req,res)=>{
    log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
    log(req.headers);
    log('');

if(req.method === 'POST'){
  if(req.url !== '/upload'){
    show(res,errPage);
    return;
  }

  req.setEncoding('binary');
  let file;
  req.on('data',(chunk)=>{
    file += chunk;
  })

  req.on('end',()=>{
    let data = file.split('\r\n');
    log('data:',data);
    let buf = data[4];
    let files = data[1].split(';');
    let fileName = qs.parse(files[2].trim())['filename'];
     fileName = fileName.slice(1, fileName.length-1);
     fs.writeFileSync(fileName, buf, {'encoding': 'binary'});
  })

  show(res,onPage);
}else{
  if(req.url === '/'){
    show(res,uploadPage);
  }else{
    show(res,errPage);
  }
}
}).listen(8080);

function show(res,page){
  res.statusCode = 404;
  res.setHeader('Content-Type','text/html');
  res.setHeader('Content-Length', page.length);
  res.end(page);
}


